/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.organization;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.Branch;
import com.qinyeit.serviceapp.entity.BranchPrivilege;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.organization.BranchPrivilegeService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.PrivilegeTemplate;
import com.qinyeit.serviceapp.service.organization.PrivilegeTemplateService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName: PrivilegeTemplatesController <br/>
 * Function: privilegeTemplate [权限模板] <br/>
 * date: 2018-11-20 13:21:52 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/organization/privilegeTemplates")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_privilegeTemplate:read",name ="权限模板",deleteAble = false)
public class PrivilegeTemplatesController extends BaseManagementController{

	@Autowired
	private PrivilegeTemplateService privilegeTemplateService;
	@Autowired
    private BranchPrivilegeService branchPrivilegeService;
	@Autowired
    private BranchService branchService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","name","codes","def","operatorName","createAt","count"};

    @RequiresPermissions("management_privilegeTemplate:show")
    @PermissionInfo(code = "management_privilegeTemplate:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<PrivilegeTemplate> privilegeTemplatePage = privilegeTemplateService.findAll(searchable);

        if(CollectionUtils.isNotEmpty(privilegeTemplatePage.getContent())){
            //已关联门店
            List<Branch> branchList = null;
            String branchs = "";
            int count =0;
            for (PrivilegeTemplate template : privilegeTemplatePage.getContent()) {
                branchs = "";
                searchable = SearchableUtils.newSearchableWithMerchantFilter();
                searchable.addSearchParam("templateId_eq",template.getId());
                branchList = branchService.findWithSort(searchable);
                count = 0;
                if(CollectionUtils.isNotEmpty(branchList)){
                    for (Branch branch : branchList) {
                        if (count<3){
                            branchs += branch.getName()+" ";
                        }else {
                            break;
                        }
                        count++;
                    }
                }
                template.setCount(StringUtils.isBlank(branchs)?"":branchs);
            }
        }
        return ok("查询成功", JSONUtils.include(privilegeTemplatePage, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("privilegeTemplate",JSONUtils.include(new PrivilegeTemplate(), keys));
        initFormDate(map); //TODO 如果没有需要初始化的数据，测则删除该行

        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_privilegeTemplate:create")
    @PermissionInfo(code = "management_privilegeTemplate:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid PrivilegeTemplate privilegeTemplate, BindingResult bindingResult){
//        if(privilegeTemplateService.exists(buildExists(null, "no", privilegeTemplate.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        privilegeTemplate.setOperator(CurrentAccountUtils.getAuthenticatedEmployeeId());
        privilegeTemplate.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());
        privilegeTemplate.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        privilegeTemplateService.save(privilegeTemplate);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute PrivilegeTemplate privilegeTemplate){
        return ok("查询成功", JSONUtils.include(privilegeTemplate, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute PrivilegeTemplate privilegeTemplate){
        QyMap map=QyMap.NEW();
        map.setv("privilegeTemplate",JSONUtils.include(privilegeTemplate, keys));
        initFormDate(map); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_privilegeTemplate:update")
    @PermissionInfo(code = "management_privilegeTemplate:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid PrivilegeTemplate privilegeTemplate,BindingResult bindingResult){
//        if(privilegeTemplateService.exists(buildExists(null, "no", privilegeTemplate.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        privilegeTemplate.setOperator(CurrentAccountUtils.getAuthenticatedEmployeeId());
        privilegeTemplate.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());
        privilegeTemplateService.update(privilegeTemplate);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_privilegeTemplate:destory")
    @PermissionInfo(code = "management_privilegeTemplate:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        //是否已关联门店
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("templateId_eq",id);
        Long count = branchService.count(searchable);
        if(count.intValue()>0){
            return fail("该模板已关联门店，不能删除");
        }
        privilegeTemplateService.logicDelete(id);
        return ok("删除成功", null);
    }


    /**
     * 查看已关联门店信息
     * @param id
     * @return
     */
    @GetMapping("/showBranch")
    public ResponseResult<String> showBranch(Long id){
        if (id==null){
            throw new BusinessRunTimeException("请选择模板",10001);
        }
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("templateId_eq",id);
        List<Branch> branchList = branchService.findWithSort(searchable);
        return ok("查询成功", branchList);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            PrivilegeTemplate privilegeTemplate = privilegeTemplateService.findById(Long.valueOf(id));
            model.addAttribute(privilegeTemplate);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //初始化 获取所有权限
        Searchable searchable = Searchable.newSearchable();
        searchable.addSearchFilter(SearchableUtils.getDeletedFilter());
        List<BranchPrivilege> branchPrivilegeList = branchPrivilegeService.findWithSort(searchable);
        qyMap.setv("branchPrivilegeList",JSONUtils.include(branchPrivilegeList,"name","code","remark"));
    }

}